//
//  TodayViewController.m
//  dpTodayWidget
//
//  Created by chuangjia on 29/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "TodayViewController.h"
#import <NotificationCenter/NotificationCenter.h>

@interface TodayViewController () <NCWidgetProviding,UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tabView;
@property(nonatomic,strong)NSMutableArray *todayArray;
@property(nonatomic,strong)NSTimer *updateTimer;
@end

@implementation TodayViewController
@synthesize tabView=_tabView;

@synthesize todayArray=_todayArray;
@synthesize updateTimer=_updateTimer;

- (id)init{
    self = [super init];
    if (self) {
       [self initUI];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //使用preferredContentSize设置大小 且只用设置高度就好了
    self.view.backgroundColor =[UIColor clearColor];
    self.preferredContentSize = CGSizeMake(0, 300);
    if (!_todayArray) {
        _todayArray = [[NSMutableArray alloc] init];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getTodayData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    if (_updateTimer) {
        [_updateTimer invalidate];
        _updateTimer=nil;
    }
    self.todayArray = nil;
    self.tabView =nil;
}
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
    // Perform any setup necessary in order to update the view.
    
    // If an error is encountered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData

    completionHandler(NCUpdateResultNewData);
    [self getTodayData];
}
- (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets
{
    return UIEdgeInsetsZero;
}
- (IBAction)menuPressed:(id)sender
{
    UIButton* button = (UIButton*)sender;
    
    if (button.tag == 1) {
        [self.extensionContext openURL:[NSURL URLWithString:@"iOSWidgetApp://action=GotoHomePage"] completionHandler:^(BOOL success) {
            NSLog(@"open url result:%d",success);
        }];
    }
}
-(void)initAutoUpdate
{
    if (_updateTimer) {
        [_updateTimer invalidate];
        _updateTimer=nil;
    }
    _updateTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(getTodayData) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_updateTimer forMode:NSDefaultRunLoopMode];
}
//================================
//
//================================
-(void)initUI
{
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300) style:UITableViewStylePlain];
    _tabView.dataSource =self;
    _tabView.delegate =self;
    [self.view addSubview:_tabView];
}
//返回有多少个Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.todayArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [_tabView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        // Create a cell to display an ingredient.
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    // Configure the cell.
    NSDictionary *dict = [self.todayArray objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor redColor];
    cell.textLabel.text=[dict objectForKey:@"goods_name"];
    return cell;
}
//==========================
//
//==========================
-(void)getTodayData
{
    NSString *strURL =[NSString stringWithFormat:@"http://api.danpin.com/shop.php?action=getTodayGoods"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"GET"];
        //
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (dcRes && [dcRes isKindOfClass:[NSDictionary class]]) {
                    id data =  [dcRes objectForKey:@"data"];
                    if (data && [data isKindOfClass:[NSArray class]]){
                        [self.todayArray removeAllObjects];
                        [self.todayArray arrayByAddingObjectsFromArray:data];
                    }
                }
                [self.tabView reloadData];
            });
        }];
    });
}
@end
